# -*- coding:utf-8 -*-
from flask import render_template, redirect, request, url_for, flash, session, current_app, jsonify
from flask_login import login_user, logout_user, login_required, current_user
from app.models.account import Staff
from app import db
from app.forms.auth.forms import LoginForm
from app.tools.log import log, get_city_by_ip
from datetime import datetime
from qiniu import Auth
from . import auth


roles = {'service': u'客服部', 'manage': u'综合管理部', 'review': u'车辆审批部', 'finance': u'财务部',
	 'hr': u'人资行政部', 'admin': u'管理层', 'director':u'客服主管', 'upload': u'业务上传',
	 'setup': u'网站设置', 'super': u'超级管理员'}

@auth.route('/login/', methods=['GET', 'POST'])
def login():
	form = LoginForm()
	if form.validate_on_submit():
		staff = Staff.query.filter_by(staff_number=form.staff_number.data).first()
		if staff and staff.verify_password(form.password.data):
			if staff.account_state != 0:
				flash(u'账户状态异常，请联系管理员')
				return render_template(('auth/login.html'), form=form)
			login_user(staff, form.remember_me.data)
			session['role'] = staff.role
			session['department'] = roles[staff.role]
			session['sid'] = staff.id
			session['staff_number'] = staff.staff_number
			session['name'] = staff.name
			session['last_login_ip'] = staff.last_login_ip if staff.last_login_ip else u'首次登录'
			session['last_login_time'] = staff.last_login_time.strftime("%Y-%m-%d %H:%M:%S") if staff.last_login_time else u'首次登录'
			session['last_login_area'] = staff.last_login_area if staff.last_login_area else u'首次登录'
			session['ip'] = request.remote_addr if request.remote_addr else u'未知'
			session['area'] = get_city_by_ip(session['ip']) if session['ip'] != u'未知' else u'未知'
			staff.last_login_ip = session['ip']
			staff.last_login_area = session['area']
			staff.last_login_time = datetime.now()
			db.session.add(staff)
			db.session.commit()
			log(u"登录系统")
			return redirect(request.args.get('next') or url_for('home.index'))
		flash(u'用户名或密码错误')
	return render_template(('auth/login.html'), form=form)

@auth.route('/logout/')
@login_required
def logout():
	logout_user()
	return redirect(url_for('auth.login'))

@auth.route('/uptoken/')
@login_required
def uptoken():
	q = Auth(current_app.config['QINIU_ACCESS_KEY'], current_app.config['QINIU_SECRET_KEY'])
	bucket_name = current_app.config['QINIU_BUCKET_NAME']
	policy={
		'deleteAfterDays': 1,
	}
	return jsonify({
		'uptoken': q.upload_token(bucket=bucket_name, expires=3600, policy=policy)
	})

@auth.before_app_request
def update_ip():
	if current_user.is_authenticated:
		ip = session.get('ip', '')
		if ip != request.remote_addr:
			ip = request.remote_addr if request.remote_addr else u'未知'
			session['area'] = get_city_by_ip(ip) if ip != u'未知' else u'未知'
	return
